package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.dao.BsActivityDao;
import io.renren.modules.app.dao.BsEmployeeDao;
import io.renren.modules.app.dao.BsMemberDao;
import io.renren.modules.app.entity.BsActivityEntity;
import io.renren.modules.app.entity.BsActivityEntityVo;
import io.renren.modules.app.entity.BsEmployeeEntity;
import io.renren.modules.app.entity.BsMemberEntity;
import io.renren.modules.app.service.BsActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


@Service("bsActivityService")
@Slf4j
public class BsActivityServiceImpl extends ServiceImpl<BsActivityDao, BsActivityEntity> implements BsActivityService {

    @Resource
    private BsActivityDao bsActivityDao ;

    @Resource
    private BsEmployeeDao bsEmployeeDao ;

    @Resource
    private BsMemberDao bsMemberDao ;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        LambdaQueryWrapper<BsActivityEntity> wrapper = new LambdaQueryWrapper<>();

        if (params.get("actiName") != null && !params.get("actiName").equals("")){
            wrapper.like(BsActivityEntity::getActiName,params.get("actiName"));
        }
        if (params.get("actiDateBegin") != null && !params.get("actiDateBegin").equals("")){
            wrapper.ge(BsActivityEntity::getActiDate,params.get("actiDateBegin"));
        }
        if (params.get("actiDateEnd") != null && !params.get("actiDateEnd").equals("")){
            wrapper.le(BsActivityEntity::getActiDate,params.get("actiDateEnd"));
        }
        IPage<BsActivityEntity> page = this.page(
                new Query<BsActivityEntity>().getPage(params),
                wrapper
        );


        for (BsActivityEntity record : page.getRecords()) {
            //活动组织者数据清洗
            List<BsEmployeeEntity> entities = bsEmployeeDao.selectList(
                    new LambdaQueryWrapper<BsEmployeeEntity>()
                            .eq(BsEmployeeEntity::getEmployeeId, record.getActiOrigin()));
            record.setActiOriginName(entities.get(0).getEmployeeName());

            //参与会员数据清洗
            List<BsActivityEntityVo> list1 = new ArrayList<>();
            if (StringUtils.isNotBlank(record.getActiMemberids())){
                String[] split = record.getActiMemberids().split(",");
                for (String s : split) {
                    List<BsMemberEntity> entities1 = bsMemberDao.selectList(
                            new LambdaQueryWrapper<BsMemberEntity>()
                                    .eq(BsMemberEntity::getMemberId, s));
                    BsActivityEntityVo bsActivityEntityVo = new BsActivityEntityVo();
                    bsActivityEntityVo.setMemberId(entities1.get(0).getMemberId());
                    bsActivityEntityVo.setMemberName(entities1.get(0).getMemberName());
                    bsActivityEntityVo.setMemberPhone(entities1.get(0).getMemberPhone());
                    list1.add(bsActivityEntityVo);
                }
            }
            record.setList(list1);
        }

        return new PageUtils(page);
    }

    @Override
    public void saveActi(BsActivityEntity bsActivity) {
        try {
            //组织者存在性校验
            String actiOrigin = bsActivity.getActiOrigin();//活动组织者
            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsEmployeeEntity::getEmployeeId,actiOrigin);
            List<BsEmployeeEntity> list = bsEmployeeDao.selectList(wrapper);
            if (list.size() < 1){
                throw new RRException("请校验活动组织者编号");
            }
            //电话格式校验
            if (!phoneValidate(bsActivity.getActiPhone())){
                throw new RRException("电话号不合法");
            }
            //会员重复性及存在性校验
            if (StringUtils.isNotBlank(bsActivity.getActiMemberids())){
                String[] split = bsActivity.getActiMemberids().split(",");
                //重复性校验
                if (checkDuplicatesBruteForce(split)){
                    throw new RRException("会员已经参加该活动,请勿重复添加");
                }
                //存在性校验
                boolean flag = true ;
                for (String s : split) {
                    LambdaQueryWrapper<BsMemberEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(BsMemberEntity::getMemberId,s);
                    List<BsMemberEntity> entityList = bsMemberDao.selectList(queryWrapper);
                    if (entityList.size() < 1){
                        flag = false ;
                        break;
                    }
                }
                if (!flag){
                    throw new RRException("请校验所添加的会员编号");
                }
            }else {
                bsActivity.setActiMemberids("");
            }
            bsActivityDao.insert(bsActivity);

        }catch (Exception e){
            log.info("报错类及其所在方法：{}","BsActivityService --> saveActi");
            log.info(e.getMessage());
            throw new RRException(e.getMessage());
        }
    }

    @Override
    public void updateActi(BsActivityEntity bsActivity) {
        try {
            //组织者存在性校验
            String actiOrigin = bsActivity.getActiOrigin();//活动组织者
            LambdaQueryWrapper<BsEmployeeEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsEmployeeEntity::getEmployeeId,actiOrigin);
            List<BsEmployeeEntity> list = bsEmployeeDao.selectList(wrapper);
            if (list.size() < 1){
                throw new RRException("请校验活动组织者编号");
            }
            //电话格式校验
            if (!phoneValidate(bsActivity.getActiPhone())){
                throw new RRException("电话号不合法");
            }
            //会员重复性及存在性校验
            if (StringUtils.isNotBlank(bsActivity.getActiMemberids())){
                String[] split = bsActivity.getActiMemberids().split(",");
                //重复性校验
                if (checkDuplicatesBruteForce(split)){
                    throw new RRException("会员已经参加该活动,请勿重复添加");
                }
                //存在性校验
                boolean flag = true ;
                for (String s : split) {
                    LambdaQueryWrapper<BsMemberEntity> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(BsMemberEntity::getMemberId,s);
                    List<BsMemberEntity> entityList = bsMemberDao.selectList(queryWrapper);
                    if (entityList.size() < 1){
                        flag = false ;
                        break;
                    }
                }
                if (!flag){
                    throw new RRException("请校验所添加的会员编号");
                }
            }else {
                bsActivity.setActiMemberids("");
            }
            bsActivityDao.updateById(bsActivity);
        }catch (Exception e){
            log.info("报错类及其所在方法：{}","BsActivityService --> updateActi");
            log.info(e.getMessage());
            throw new RRException(e.getMessage());
        }
    }


    //校验电话号公共方法
    private boolean phoneValidate(String phoneNumber){
        if (phoneNumber != null && !phoneNumber.isEmpty()){
            boolean matches = Pattern.matches(
                    "^1[3-9]\\d{9}$|" +
                            "^1[3-9]\\d{1}[-\\s]\\d{4}[-\\s]\\d{4}$|" +
                            "^\\(1[3-9]\\d{1}\\)\\d{4}-\\d{4}$|" +
                            "^(?:\\(\\+\\d{2}\\)|\\+\\d{2})(\\d{11})$|" +
                            "^0\\d{3}-\\d{7}$|" +
                            "^0\\d{2}-\\d{8}$", phoneNumber);

            return matches;
        }
        return false;
    }

    //校验数组是否有重复元素公共方法
    private boolean checkDuplicatesBruteForce(String[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i].equals(arr[j])) {
                    return true;
                }
            }
        }
        return false;
    }

}
